import React, { useState, useEffect } from 'react';
import Select from 'react-select';
import { useNavigate, useLocation } from 'react-router-dom';

// 获取当前文件名（去掉路径和扩展名）
const getCurrentFileName = () => {
    const path = import.meta.url; // 获取当前文件的URL路径
    const fileNameWithExtension = path.split('/').pop(); // 获取文件名（带扩展名）
    const fileName = fileNameWithExtension.split('.').shift(); // 去掉扩展名
    return fileName;
};

const AddConfigPage = () => {
    const [tableNames, setTableNames] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [selectedTable, setSelectedTable] = useState(null);
    const [pageName, setPageName] = useState(getCurrentFileName()); // 默认页面名称是当前文件名
    const navigate = useNavigate();
    const location = useLocation();
    const [showMainTableSelect, setShowMainTableSelect] = useState(false);
    const [showRelatedTableSelect, setShowRelatedTableSelect] = useState(false);
    const [mainTableFields, setMainTableFields] = useState([]);
    const [relatedTableFields, setRelatedTableFields] = useState([]);
    const [mainTableAdded, setMainTableAdded] = useState(false); // 记录是否点击了新增主表
    const [mainTableColumns, setMainTableColumns] = useState([]); // 存储主表的列信息
    const [columnTypeOptions, setColumnTypeOptions] = useState([]); // 存储数据类型选项
    const [formTypeOptions, setformTypeOptions] = useState([]); // 存储数据类型选项
    const [showFormStatusPopup, setShowFormStatusPopup] = useState(false); // 控制表单状态弹窗的显示和隐藏
    const [formStatusOption, setFormStatusOption] = useState(null); // 存储表单状态下拉框的选择值
    const [formStatusInputValue, setFormStatusInputValue] = useState(''); // 存储表单状态输入框的值
    const [currentColumnIndex, setCurrentColumnIndex] = useState(null); // 记录当前点击的列的索引
    const [savedFormStatusData, setSavedFormStatusData] = useState({}); // 存储保存的表单状态数据，键为列索引，值为{ formStatusValue, formStatusInputValue }
    const [isFormTypeLoading, setIsFormTypeLoading] = useState(false);
    // 修改columnOptions结构为：
    const [columnOptions, setColumnOptions] = useState({
        main: {},     // 主表配置 { [columnIndex]: { ... } }
        related: []   // 关联表配置数组，每个元素对应一个关联表 { [columnIndex]: { ... } }
    });
    const [selectedMainTable, setSelectedMainTable] = useState(null); // 新增状态来存储主表选中的值
    const [selectedRelatedTable, setSelectedRelatedTable] = useState(null); // 新增状态来存储关联表选中的值
    const [selectedRelatedTableColumns, setSelectedRelatedTableColumns] = useState([]); // 存储关联表的列信息
    const [relatedTables, setRelatedTables] = useState([]); // 存储所有关联表的数据
    const [pageNameInputValue, setPageNameInputValue] = useState('');
    // 调用后端接口获取所有表名
    const fetchTableNames = async () => {
        setIsLoading(true);
        try {
            const response = await fetch('http://127.0.0.1:9991/api/admin/demo/allTableName');
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            if (result.code === 200 && Array.isArray(result.data)) {
                const options = result.data.map((name) => ({ value: name, label: name }));
                setTableNames(options);
                handleSelectChange(options);
            }
        } catch (error) {
            console.error('Error fetching table names:', error);
        } finally {
            setIsLoading(false);
        }
    };

    // 调用后端接口获取表字段
    const fetchTableFields = async (tableName) => {
        try {
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/tableFields?tableName=${tableName}`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            if (result.code === 200 && Array.isArray(result.data)) {
                return result.data;
            }
            return [];
        } catch (error) {
            console.error('Error fetching table fields:', error);
            return [];
        }
    };

    // 调用后端接口获取主表的所有列信息
    const fetchMainTableColumns = async (tableName) => {
        try {
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/getAllColumns?tableName=${tableName}`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            if (result.code === 200 && Array.isArray(result.data)) {
                return result.data;
            }
            return [];
        } catch (error) {
            console.error('Error fetching main table columns:', error);
            return [];
        }
    };

    // 调用后端接口获取数据类型选项
    const fetchColumnTypeOptions = async () => {
        try {
            const response = await fetch('http://127.0.0.1:9991/api/admin/demo/getColumnType?parentColumn=columnType');
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            if (result.code === 200 && Array.isArray(result.data)) {
                const options = result.data.map((type) => ({ value: type, label: type }));
                setColumnTypeOptions(options);
            }
        } catch (error) {
            console.error('Error fetching column type options:', error);
        }
    };

    // 用于处理表单状态选项选择时调用后端接口
    const handleFormStatusOptionSelected = async () => {
        setIsFormTypeLoading(true);
        try {
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/getColumnType?parentColumn=formType`);
            if (!response.ok) throw new Error('Network response was not ok');
            const result = await response.json();
            if (result.code === 200 && Array.isArray(result.data)) {
                const options = result.data.map((type) => ({ value: type, label: type }));
                setformTypeOptions(options);
            }
        } catch (error) {
            console.error('Error fetching form status:', error);
        } finally {
            setIsFormTypeLoading(false);
        }
    };

    useEffect(() => {
        fetchTableNames();
        fetchColumnTypeOptions();
        handleFormStatusOptionSelected(); // 初始化时加载 formTypeOptions
    }, []);

    // 处理下拉框选择
    const handleSelectChange = (selectedOption) => {
        setSelectedTable(selectedOption);
    };

    // 处理输入框变化
    const handlePageNameChange = (event) => {
        // setPageName(event.target.value);
        setPageNameInputValue(event.target.value);

    };

    // 处理保存按钮点击
    const handleSaveClick = () => {
        if (!selectedMainTable) {
            alert('请选择主表');
            return;
        }
        // 生成配置 JSON
        const configJson = generateConfigJson();
        const result = {
            "path": pageNameInputValue,
            "tableName": selectedMainTable.value + ";" + relatedTables.map(table => table.selectedTable.value).join(";"),
            "content": configJson
        };
        console.log('生成的配置:', result);
        // 调用 API 保存配置
        fetch('http://127.0.0.1:9991/api/admin/demo/saveConfig', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(result)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    navigate('/config'); // 跳转回配置页面
                }
            })
            .catch(error => console.error('保存失败:', error));
    };
    
    // 获取当前路由名称（简单处理路径，你可以根据实际情况调整）
    const currentRouteName = location.pathname.split('/').pop();

    // 处理新增主表按钮点击
    const handleAddMainTableClick = () => {
        const newShowMainTableSelect = !showMainTableSelect;
        setShowMainTableSelect(newShowMainTableSelect);
        setMainTableFields([]);
        setMainTableAdded(newShowMainTableSelect); // 更新主表添加状态
        if (!newShowMainTableSelect) {
            // 如果取消新增主表，同步取消新增关联表
            setShowRelatedTableSelect(false);
            setRelatedTableFields([]);
            setMainTableColumns([]); // 清空主表列信息
        }
    };

    // 处理新增关联表按钮点击
    const handleAddRelatedTableClick = () => {
        const newShowRelatedTableSelect = !showRelatedTableSelect;
        setShowRelatedTableSelect(newShowRelatedTableSelect);
        setRelatedTableFields([]);
        if (!newShowRelatedTableSelect) {
            // 如果取消新增主表，同步取消新增关联表
            setShowRelatedTableSelect(false);
            setRelatedTableFields([]);
            setSelectedRelatedTableColumns([]); // 清空主表列信息
        }
        setRelatedTables([...relatedTables, { selectedTable: null, columns: [] }]);
    };

    // 处理主表下拉框选择
    const handleMainTableSelectChange = async (selectedOption) => {
        const fields = await fetchTableFields(selectedOption.value);
        setMainTableFields(fields);
        const columns = await fetchMainTableColumns(selectedOption.value);
        setMainTableColumns(columns);
        setSelectedMainTable(selectedOption); // 更新主表选中的值
    };

    // 处理关联表下拉框选择
    const handleRelatedTableSelectChange = async (index, selectedOption) => {
        const fields = await fetchTableFields(selectedOption.value);
        const columns = await fetchMainTableColumns(selectedOption.value);
        const updatedRelatedTables = [...relatedTables];
        updatedRelatedTables[index] = {
            selectedTable: selectedOption,
            columns: columns
        };
        setRelatedTables(updatedRelatedTables);
    };
    
    const handleFormStatusSelectClick = (index) => {
        setCurrentColumnIndex(index);
        const savedData = savedFormStatusData[index] || {};
        const selectedOption = formTypeOptions.find(opt => opt.value === savedData.formStatusValue);
        setFormStatusOption(selectedOption || null);
        setFormStatusInputValue(savedData.formStatusInputValue || '');
        setShowFormStatusPopup(true);
    };

    // 处理表单状态弹窗中的下拉框选择
    const handleFormStatusOptionChange = (selectedOption) => {
        setFormStatusOption(selectedOption);
        handleFormStatusOptionSelected(selectedOption);
    };

    // 处理表单状态弹窗中的输入框变化
    const handleFormStatusInputChange = (event) => {
        setFormStatusInputValue(event.target.value);
    };

    // 关闭表单状态弹窗
    const handleCloseFormStatusPopup = () => {
        if (currentColumnIndex !== null) {
            const data = {
                formStatusValue: formStatusOption ? formStatusOption.value : null, // 仅保存value
                formStatusInputValue: formStatusInputValue
            };
            setSavedFormStatusData((prevData) => ({
                ...prevData,
                [currentColumnIndex]: data
            }));
        }
        setShowFormStatusPopup(false);
    };

    // 选择下拉框的选项
    const isOrNoOptions = [
        { value: '是', label: '是' },
        { value: '否', label: '否' }
    ];

    // 修改handleConfirmClick和handleCloseFormStatusPopup中的保存逻辑：
    const handleConfirmClick = () => {
        if (currentColumnIndex !== null) {
            const data = {
                formStatusValue: formStatusOption ? formStatusOption.value : null, // 仅保存value
                formStatusInputValue: formStatusInputValue
            };
            setSavedFormStatusData((prevData) => ({
                ...prevData,
                [currentColumnIndex]: data
            }));
        }
        handleCloseFormStatusPopup();
    };

    // 修改处理函数：
    const handleColumnOptionChange = (tableType, tableIndex, columnIndex, field, value) => {
        setColumnOptions(prev => {
        if (tableType === 'main') {
            return {
            ...prev,
            main: {
                ...prev.main,
                [columnIndex]: {
                ...prev.main[columnIndex],
                [field]: value
                }
            }
            };
        } else {
            const newRelated = [...prev.related];
            newRelated[tableIndex] = {
            ...newRelated[tableIndex],
            [columnIndex]: {
                ...(newRelated[tableIndex]?.[columnIndex] || {}),
                [field]: value
            }
            };
            return {...prev, related: newRelated};
        }
        });
    };

    const generateConfigJson = () => {
        // 1. 获取路径
        const path = pageNameInputValue; // 或根据实际需求调整
        // 2. 构建表数组
        const tables = [];
        if (selectedMainTable && mainTableColumns.length > 0) {
            const columns = mainTableColumns.map((column, index) => {
                const options = columnOptions.main[index] || {};
                const formStatus = savedFormStatusData[index] || {};
                // 3. 构建每个字段的配置
                return {
                    columnName: column.columnName,
                    notNull: options.notNull === '是',
                    primary_Key: options.primaryKey === '是',
                    autoIncrement: options.autoIncrement === '是',
                    point: parseInt(options.point) || 0,
                    remark: options.remark || '',
                    columnType: options.columnType || '',
                    display: options.display === '是',
                    formType: {
                        type: formStatus.formStatusValue || '',
                        date: formStatus.formStatusInputValue || ''
                    },
                    isSearch: options.isSearch === '是',
                    minLength: parseInt(options.minLength) || null,
                    maxLength: parseInt(options.maxLength) || null,
                    regEx: options.regEx ? options.regEx : null // 根据实际需求调整正则规则
                };
            });
            // 4. 添加主表信息
            tables.push({
                tableName: selectedMainTable.value,
                isMaster: true,
                columns: columns
            });
        }
        // 添加关联表信息
        relatedTables.map((relatedTable, tableIndex) => {
            if (relatedTable.selectedTable && relatedTable.columns.length > 0) {
                const relatedColumns = relatedTable.columns.map((column, index) => {
                    const relatedColumnOptions = columnOptions.related[tableIndex]?.[index] || {};
                    const relatedFormStatus = savedFormStatusData[index] || {};
                    return {
                        columnName: column.columnName,
                        notNull: relatedColumnOptions.notNull === '是',
                        primary_Key: relatedColumnOptions.primaryKey === '是',
                        autoIncrement: relatedColumnOptions.autoIncrement === '是',
                        point: parseInt(relatedColumnOptions.point) || 0,
                        remark: relatedColumnOptions.remark || '',
                        columnType: relatedColumnOptions.columnType || '',
                        display: relatedColumnOptions.display === '是',
                        formType: {
                            type: relatedFormStatus.formStatusValue || '',
                            date: relatedFormStatus.formStatusInputValue || ''
                        },
                        isSearch: relatedColumnOptions.isSearch === '是',
                        minLength: parseInt(relatedColumnOptions.minLength) || null,
                        maxLength: parseInt(relatedColumnOptions.maxLength) || null,
                        regEx: relatedColumnOptions.regEx ? relatedColumnOptions.regEx : null
                    };
                });
                tables.push({
                    tableName: relatedTable.selectedTable.value,
                    isMaster: false,
                    columns: relatedColumns
                });
            }
        });
        // 5. 返回最终 JSON
        return {
            path: path,
            tables: tables
        };
    };

    return (
        <div style={{ padding: '20px' }}>
            <div style={{ marginBottom: '20px' }}>
                <label htmlFor="pageName">页面名称：</label>
                <input
                    id="pageName"
                    type="text"
                    value={pageNameInputValue}
                    onChange={handlePageNameChange}
                    style={{ marginBottom: '20px', padding: '5px', width: '300px' }}
                />
            </div>
            <button onClick={handleSaveClick}>保存</button>
            <button onClick={handleAddMainTableClick} style={{ marginLeft: '10px' }}>新增主表</button>
            <button
                onClick={handleAddRelatedTableClick}
                style={{ marginLeft: '10px' }}
                disabled={!mainTableAdded} // 根据主表添加状态禁用按钮
            >
                新增关联表
            </button>
            {showMainTableSelect && (
                <div style={{ marginTop: '20px' }}>
                    <Select
                        isLoading={isLoading}
                        options={tableNames}
                        onChange={handleMainTableSelectChange}
                        placeholder="选择主表"
                    />
                    {mainTableFields.length > 0 && (
                        <div style={{ marginTop: '10px' }}>
                            <h4>主表字段：</h4>
                            <ul>
                                {mainTableFields.map((field, index) => (
                                    <li key={index}>{field}</li>
                                ))}
                            </ul>
                        </div>
                    )}
                    {mainTableColumns.length > 0 && (
                        <div style={{ marginTop: '20px' }}>
                            <table border="1" style={{ width: '100%', borderCollapse: 'collapse' }}>
                                <thead>
                                    <tr>
                                        <th>字段名</th>
                                        <th>是否非空</th>
                                        <th>是否主键</th>
                                        <th>是否自增</th>
                                        <th>小数点</th>
                                        <th>备注</th>
                                        <th>数据类型</th>
                                        <th>展示状态</th>
                                        <th>表单状态</th>
                                        <th>是否为搜索条件</th>
                                        <th>前端校验最小长度</th>
                                        <th>字段最大长度</th>
                                        <th>前端正则校验规则</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {mainTableColumns.map((column, index) => (
                                        <tr key={index}>
                                            <td>{column.columnName}</td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.main[index]?.notNull || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('main',null,index, 'notNull', selected.value)}
                                                    placeholder="选择是否非空"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.main[index]?.primaryKey || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('main',null,index, 'primaryKey', selected.value)}
                                                    placeholder="选择是否主键"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.main[index]?.autoIncrement || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('main',null,index, 'autoIncrement', selected.value)}
                                                    placeholder="选择是否自增"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.main[index]?.point || ''}
                                                    onChange={(e) => handleColumnOptionChange('main',null,index, 'point', e.target.value)}
                                                    placeholder="小数点位数"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.main[index]?.remark || ''}
                                                    onChange={(e) => handleColumnOptionChange('main',null,index, 'remark', e.target.value)}
                                                    placeholder="备注"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={columnTypeOptions}
                                                    value={columnTypeOptions.find(opt => opt.value === (columnOptions.main[index]?.columnType || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('main',null,index, 'columnType', selected.value)}
                                                    placeholder="选择数据类型"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.main[index]?.display || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('main',null,index, 'display', selected.value)}
                                                    placeholder="选择展示状态"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <button onClick={() => handleFormStatusSelectClick(index)} style={{ width: '100%' }}>
                                                    表单详情
                                                </button>
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.main[index]?.isSearch || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('main',null,index, 'isSearch', selected.value)}
                                                    placeholder="选择是否为搜索条件"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.main[index]?.minLength || ''}
                                                    onChange={(e) => handleColumnOptionChange('main',null,index, 'minLength', e.target.value)}
                                                    placeholder="前端校验最小长度"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.main[index]?.maxLength || ''}
                                                    onChange={(e) => handleColumnOptionChange('main',null,index, 'maxLength', e.target.value)}
                                                    placeholder="字段最大长度"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.main[index]?.regEx || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('main',null,index, 'regEx', selected.value)}
                                                    placeholder="选择前端正则校验规则"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
            )}
            {relatedTables.map((relatedTable, tableIndex) => (
                <div key={tableIndex} style={{ marginTop: '20px' }}>
                    <Select
                        isLoading={isLoading}
                        options={tableNames}
                        onChange={(selectedOption) => handleRelatedTableSelectChange(tableIndex, selectedOption)}
                        placeholder="选择关联表"
                    />
                    {relatedTable.columns.length > 0 && (
                        <div style={{ marginTop: '10px' }}>
                            <h4>关联表字段：</h4>
                            <table border="1" style={{ width: '100%', borderCollapse: 'collapse' }}>
                                <thead>
                                    <tr>
                                        <th>字段名</th>
                                        <th>是否非空</th>
                                        <th>是否主键</th>
                                        <th>是否自增</th>
                                        <th>小数点</th>
                                        <th>备注</th>
                                        <th>数据类型</th>
                                        <th>展示状态</th>
                                        <th>表单状态</th>
                                        <th>是否为搜索条件</th>
                                        <th>前端校验最小长度</th>
                                        <th>字段最大长度</th>
                                        <th>前端正则校验规则</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {relatedTable.columns.map((column, colIndex) => (
                                        <tr key={colIndex}>
                                            <td>{column.columnName}</td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.related[tableIndex]?.[colIndex]?.notNull || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('related',tableIndex,colIndex, 'notNull', selected.value)}
                                                    placeholder="选择是否非空"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.related[tableIndex]?.[colIndex]?.primaryKey || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('related',tableIndex,colIndex, 'primaryKey', selected.value)}
                                                    placeholder="选择是否主键"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.related[tableIndex]?.[colIndex]?.autoIncrement || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('related',tableIndex,colIndex, 'autoIncrement', selected.value)}
                                                    placeholder="选择是否自增"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.related[tableIndex]?.[colIndex]?.point || ''}
                                                    onChange={(e) => handleColumnOptionChange('related',tableIndex,colIndex, 'point', e.target.value)}
                                                    placeholder="小数点位数"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.related[tableIndex]?.[colIndex]?.remark || ''}
                                                    onChange={(e) => handleColumnOptionChange('related',tableIndex,colIndex, 'remark', e.target.value)}
                                                    placeholder="备注"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={columnTypeOptions}
                                                    value={columnTypeOptions.find(opt => opt.value === (columnOptions.related[tableIndex]?.[colIndex]?.columnType || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('related',tableIndex,colIndex, 'columnType', selected.value)}
                                                    placeholder="选择数据类型"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.related[tableIndex]?.[colIndex]?.display || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('related',tableIndex,colIndex, 'display', selected.value)}
                                                    placeholder="选择展示状态"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <button onClick={() => handleFormStatusSelectClick(colIndex)} style={{ width: '100%' }}>
                                                    表单详情
                                                </button>
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.related[tableIndex]?.[colIndex]?.isSearch || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('related',tableIndex,colIndex, 'isSearch', selected.value)}
                                                    placeholder="选择是否为搜索条件"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.related[tableIndex]?.[colIndex]?.minLength || ''}
                                                    onChange={(e) => handleColumnOptionChange('related',tableIndex,colIndex, 'minLength', e.target.value)}
                                                    placeholder="前端校验最小长度"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <input
                                                    type="text"
                                                    value={columnOptions.related[tableIndex]?.[colIndex]?.maxLength || ''}
                                                    onChange={(e) => handleColumnOptionChange('related',tableIndex,colIndex, 'maxLength', e.target.value)}
                                                    placeholder="字段最大长度"
                                                    style={{ width: '90%' }}
                                                />
                                            </td>
                                            <td>
                                                <Select
                                                    options={isOrNoOptions}
                                                    value={isOrNoOptions.find(opt => opt.value === (columnOptions.related[tableIndex]?.[colIndex]?.regEx || ''))}
                                                    onChange={(selected) => handleColumnOptionChange('related',tableIndex,colIndex, 'regEx', selected.value)}
                                                    placeholder="选择前端正则校验规则"
                                                    style={{ width: '100%' }}
                                                />
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
            ))}
            {showFormStatusPopup && (
                <div
                    style={{
                        position: 'fixed',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                        backgroundColor: '#fff',
                        padding: '20px',
                        boxShadow: '0 0 10px rgba(0, 0, 0, 0.3)',
                        zIndex: 1000,
                        width: '400px',
                        borderRadius: '5px'
                    }}
                >
                    <Select
                        isLoading={isFormTypeLoading}
                        options={formTypeOptions}
                        value={formStatusOption}
                        onChange={handleFormStatusOptionChange}
                        placeholder="选择表单状态选项"
                        style={{ width: '48%' }}
                    />
                    <input
                        type="text"
                        value={formStatusInputValue}
                        onChange={handleFormStatusInputChange}
                        placeholder="输入表单状态值"
                        style={{ padding: '5px', width: '96%' }} // 调整输入框宽度
                    />
                    <button onClick={handleConfirmClick} style={{ width: '48%' }}>
                        确认
                    </button>
                    <button onClick={handleCloseFormStatusPopup} style={{ width: '48%' }}>
                        关闭
                    </button>
                </div>
            )}
        </div>
    );
};

export default AddConfigPage;
